#include "CollapseItemWidget.h"
#include <QTransform>

CollapseItemWidget::CollapseItemWidget(QWidget* parent)
	: QWidget(parent)
	, ui(new Ui::CollapseItemWidgetClass())
{
	ui->setupUi(this);
	setAttribute(Qt::WA_StyledBackground);
	ui->headerWgt->installEventFilter(this);
	ui->contentWgt->hide();
	refreshMinHeight();
}

CollapseItemWidget::~CollapseItemWidget()
{
	delete ui;
}

void CollapseItemWidget::setContentWidget(QWidget* contentWgt)
{
	contentWgt->setParent(ui->contentWgt);
	m_contentWgt = contentWgt;
}

bool CollapseItemWidget::eventFilter(QObject* watched, QEvent* ev)
{
	if (watched == ui->headerWgt) {
		if (ev->type() == QEvent::MouseButtonPress || ev->type() == QEvent::MouseButtonDblClick) {
			m_isSelected = !m_isSelected;
			ui->contentWgt->setVisible(m_isSelected);
			refreshMinHeight();
			setExpand(m_isSelected);
			emit sigSelected(m_isSelected);
		}
	}
	return QWidget::eventFilter(watched, ev);
}

void CollapseItemWidget::resizeEvent(QResizeEvent* event)
{
	QWidget::resizeEvent(event);
}

void CollapseItemWidget::refreshMinHeight()
{
	const QMargins margin = layout()->contentsMargins();
	const int minHeaderHeight = ui->headerWgt->minimumHeight();
	if (m_isSelected) {
		const int minContentHeight = m_contentWgt ? m_contentWgt->minimumHeight() : ui->contentWgt->minimumHeight();
		const int minHeight = minHeaderHeight + minContentHeight + margin.top() + margin.bottom();
		setMinimumHeight(minHeight);
		//resize(width(), minHeight);
	}
	else {
		const int minHeight = minHeaderHeight + margin.top() + margin.bottom();
		setMinimumHeight(minHeight);
		//resize(width(), minHeight);
	}
}

void CollapseItemWidget::setExpand(bool isExpand)
{
	QImage image(":/images/上.png");
	if (isExpand) {
		// 将图像旋转180度
		QTransform transform;
		transform.rotate(180);
		QImage rotatedImage = image.transformed(transform);
		// 设置旋转后的图像到headerWgt中
		ui->headerWgt->setExpandImage(rotatedImage);
	}
	else {
		ui->headerWgt->setExpandImage(image);
	}
}
